package com.sheep.opt;

import org.apache.log4j.Logger;

import java.text.MessageFormat;
import java.util.MissingResourceException;
import java.util.ResourceBundle;

/**
 * Created by IntelliJ IDEA.
 * User: wnj
 * Date: 2010-11-15
 * Time: 19:51:59
 * To change this template use File | Settings | File Templates.
 */
public class Resources {
	private static Logger log = Logger.getLogger(Resources.class);
    /** 国际化资源 */
	public static ResourceBundle resourceBundle;

	public static void init() {
		resourceBundle = ResourceBundle.getBundle("resources.application");
//		resourceBundle = ResourceBundle.getBundle("resources.application", Locale.getDefault());
	}

	public static void close() {
		resourceBundle = null;
	}

    public static String myString() {
        return resourceBundle.toString();
    }

	/**
     * 从资源文件中返回字符串 我们不希望程序崩溃，所以如果没有找到Key，就直接返回Key
     */
    public static String getString(String key) {
        try {
            if(!resourceBundle.containsKey(key)) {
                return key;
            }
            return resourceBundle.getString(key);
        } catch (MissingResourceException e) {
        	log.error(e);
        	e.printStackTrace();
            return key;
        } catch (NullPointerException e) {
        	log.error(e);
            return "!" + key + "!";
        }
    }

    /**
     * 从资源文件中返回字符串 我们不希望程序崩溃，所以如果没有找到Key，就直接返回Key
     */
    public static String getString(String key, Object[] args) {
        try {
            return MessageFormat.format(getString(key), args);
        } catch (MissingResourceException e) {
        	log.error(e);
        	e.printStackTrace();
            return key;
        } catch (NullPointerException e) {
        	log.error(e);
            return "!" + key + "!";
        }
    }
}
